package com.wootion.cims.shiro.config;
import com.wootion.cims.dao.SysRoleDao;
import com.wootion.cims.general.utils.RedisUtil;
import com.wootion.cims.module.systemsetting.user.model.User;
import com.wootion.cims.shiro.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class JwtRealm extends AuthorizingRealm {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SysRoleDao sysRoleDao;
    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取到安全数据
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //以下可以设置角色和权限信息
        String roleKey = sysRoleDao.findByRoles(user.getId());
        Set<String> roleSet = new HashSet<>();
        roleSet.add(roleKey);
        info.setRoles(roleSet);
        info.setStringPermissions(null);
        return info;
    }



    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        String id;
        try {
            id = JwtUtil.getToken(token);
        } catch (Exception e) {
            log.error("token拼写错误");
            throw new AuthenticationException("token拼写错误");
        }
        if (id == null) {
            log.error("token无效！");
            throw new AuthenticationException("token无效");
        }
        //根据token中的userid去查询数据库
        User user = (User) redisUtil.getCacheObject("user:" + token);
        if (user == null) {
            log.error("token已经过期，请重新登陆)");
            throw new AuthenticationException("token已经过期!请重新登陆");
        }
        return new SimpleAuthenticationInfo(user, token, "JwtRealm");
    }
}
